<?php

namespace app\api\controller;
use think\admin\Controller;
use think\facade\Log;
use think\Request;
/**
 * Class Shopcart
 * @package app\api\controller
 */
class Shopcart extends Controller
{
    private $default_type = 'json';

    protected $middleware = ['check'];

    public function __construct(Request $request){
        $this->request = $request;
    }
    /**
     * GET
     * 购物车列表
     * @return array|string
     */
    public function index(){
        if($this->request->debug != 1){
            $result = [];
            $tokeninfo = $this->request->tokeninfo;
            if(empty($tokeninfo)){
                return \Tools::returnMsg(true,[],$this->default_type);
            }
            $shopCartModel = new \app\api\model\ShopCart();
            $shopCartList = $shopCartModel->getLists(array(
                'user_id'   => $tokeninfo['id']
            ),'goods_id,goods_sku_id,goods_num,select');
            if(empty($shopCartList) === FALSE){
                $goodsModel = new \app\api\model\ShopGoods();
                $detailModel = new \app\api\model\ShopGoodsItem();
                $rate = 1;
                $can_show_newActiviy = sysconf('base.can_show_newActiviy');
                if($can_show_newActiviy == 1){
                    $rate = sysconf("base.newopenActivity_rate");
                }
                foreach($shopCartList as $sk=>$v){
                    $detail = $detailModel->getOne(array(
                        'id'    =>$v['goods_id']
                    ),'id,name,cover as img,goods_code,goods_sku,goods_spec,stock_sales,stock_total,price_selling as price,price_market,number_virtual');
                    if(empty($detail) === FALSE){
                        $goodsinfo = $goodsModel->getOne(array(
                            'code'  => $detail['goods_code']
                        ),'id');
                        if(empty($goodsinfo) === FALSE){
                            if(empty($detail['stock_sales'])) $detail['stock_sales'] = 0;
                            if(empty($detail['number_virtual'])) $detail['number_virtual'] = 0;
                            $shopCartList[$sk]['number'] = $detail['stock_sales'] + $detail['number_virtual'];
                            $shopCartList[$sk]['price'] = '￥'.sprintf("%.2f",$detail['price'] * $rate/100);
                            $shopCartList[$sk]['price_market'] = '￥'.sprintf("%.2f",$detail['price_market']/100);
                            $shopCartList[$sk]['spec'] = $detail['goods_spec'];
                            $shopCartList[$sk]['img'] = $detail['img'];
                            $shopCartList[$sk]['name'] = $detail['name'];
                            $shopCartList[$sk]['stock_total'] = $detail['stock_total'];
                            $shopCartList[$sk]['parent_goods_id'] = $goodsinfo['id'];
                        }else{
                            unset($shopCartList[$sk]);
                        }
                    }else{
                        unset($shopCartList[$sk]);
                    }
                }
                $result = array_values($shopCartList);
            }else{
                return \Tools::returnMsg(true,[],$this->default_type);
            }
        }else{
             $result = array(
                array(
                    'goods_ids'=>1,
                    'img'=>'/static/img/goods/p1.jpg',
                    'name'=>'商品标题商品标题商品标题商品标题商品标题商品标题商品标题商品标题商品标题商品标题',
                    'spec'=>'规格:S码',
                    'price' => 127.5,
                    'price_market' => 127.5,
                    'number'=>4,
                    'select'=>1
                ),
                array(
                    'goods_ids'=>2,
                    'img'=>'/static/img/goods/p2.jpg',
                    'name'=>'商品标题商品标题商品标题商品标题商品标题商品标题商品标题商品标题商品标题商品标题',
                    'spec'=>'规格:S码',
                    'price' => 127.5,
                    'price_market' => 127.5,
                    'number'=>4,
                    'select'=>0
                ),
                array(
                    'goods_ids'=>3,
                    'img'=>'/static/img/goods/p3.jpg',
                    'name'=>'商品标题商品标题商品标题商品标题商品标题商品标题商品标题商品标题商品标题商品标题',
                    'spec'=>'规格:S码',
                    'price' => 127.5,
                    'price_market' => 127.5,
                    'number'=>4,
                    'select'=>1
                ),
            );
        }
        return \Tools::returnMsg(true,$result,$this->default_type);
    }
    /**
     * POST
     * 添加购物车
     * @return array|string
     */
    public function add(){
        if($this->request->debug != 1){
            $goods_id = input('id','','trim,intval');//商品id
            $goods_num = input('num',1,'trim,intval');//加入数量
            $tokeninfo = $this->request->tokeninfo;
            if(empty($tokeninfo)){
                return \Tools::returnMsg(false,array(
                    'code'  => '100001',
                    'message'=>'未登录  请先登录'
                ),$this->default_type);
            }
            if(empty($goods_id)){
                return \Tools::returnMsg(false,array(
                    'code'  => '10004',
                    'message'=>'参数有误'
                ),$this->default_type);
            }
            //查一下库存
            $detailModel = new \app\api\model\ShopGoodsItem();
            $detail = $detailModel->getOne(array(
                'id'    => $goods_id,
                'status'=> 1
            ),'stock_total,goods_sku');
            if(empty($detail)){
                 return \Tools::returnMsg(false,array(
                    'code'  => '10004',
                    'message'=>'参数有误'
                ),$this->default_type);
            }
            if($detail['stock_total'] < $goods_num){
                return \Tools::returnMsg(false,array(
                    'code'  => '10005',
                    'message'=>'库存不足'
                ),$this->default_type);
            }
            $shopCartModel = new \app\api\model\ShopCart();
            //查一下  购物车中是否有  若有  更新数量
            $where = array(
                        'user_id'   => $tokeninfo['id'],
                        'goods_id' => $goods_id
                    );
            $cartInfo = $shopCartModel->getOne($where,'id,goods_num');
            if(empty($cartInfo)) {
                $cartData = array(
                    'goods_id' => $goods_id,
                    'goods_sku_id' => $detail['goods_sku'],
                    'goods_num' => $goods_num,
                    'user_id' => $tokeninfo['id'],
                    'create_at' => \Tools::getDateTimeByTime(),
                    'update_at' => \Tools::getDateTimeByTime(),
                );
                $res = $shopCartModel->addData($cartData);
            }else{
                $res = $shopCartModel->incNum($where,'goods_num',$goods_num);
            }
            if($res){
                 return \Tools::returnMsg(true,$res,$this->default_type);
            }else{
                 return \Tools::returnMsg(false,array(
                    'code'  => '10006',
                    'message'=>'添加失败'
                ),$this->default_type);
            }
        }else{
            return \Tools::returnMsg(true,array(),$this->default_type);
        }
    }
    /**
     * PUT
     * 更新购物车
     * @return array|string
     */
    public function update(){
        if($this->request->debug != 1){
            $goods_id = input('id','','trim,intval');//商品id
            $goods_num = input('num',0,'trim,intval');//加入数量
            $select = input('select',0,'trim,intval');//更改数量的时候  1选中 0不选择
            $type  = input('type',0,'trim,intval');//0  加  1  减   2  传数字
            \Common::addlog('updatecart',$goods_id);
            $tokeninfo = $this->request->tokeninfo;
            if(empty($tokeninfo)){
                return \Tools::returnMsg(false,array(
                    'code'  => '100001',
                    'message'=>'未登录  请先登录'
                ),$this->default_type);
            }
            if(empty($goods_id)){
                return \Tools::returnMsg(false,array(
                    'code'  => '10004',
                    'message'=>'参数有误'
                ),$this->default_type);
            }
            //查一下库存
            $detailModel = new \app\api\model\ShopGoodsItem();
            $detail = $detailModel->getOne(array(
                'id'    => $goods_id,
                'status'=> 1
            ),'stock_total,goods_sku');
            if(empty($detail)){
                 return \Tools::returnMsg(false,array(
                    'code'  => '10004',
                    'message'=>'参数有误'
                ),$this->default_type);
            }
            $shopCartModel = new \app\api\model\ShopCart();
            $where = array(
                        'user_id'   => $tokeninfo['id'],
                        'goods_id' => $goods_id
                    );
            $cartInfo = $shopCartModel->getOne($where,'id,goods_num');
            if(empty($cartInfo)){
                return \Tools::returnMsg(false,array(
                    'code'  => '10004',
                    'message'=>'参数有误'
                ),$this->default_type);
            }
            if($type == 0){
                if($detail['stock_total'] < $goods_num){
                    return \Tools::returnMsg(false,array(
                        'code'  => '10005',
                        'message'=>'库存不足'
                    ),$this->default_type);
                }
            }else if($type == 2){
                if($cartInfo['goods_num'] < $goods_num){
                    if($detail['stock_total'] < $goods_num){
                        return \Tools::returnMsg(false,array(
                            'code'  => '10005',
                            'message'=>'库存不足'
                        ),$this->default_type);
                    }
                }
            }
            if($type == 2){
                $res = $shopCartModel->saveData($where,array(
                    'goods_num' => $goods_num,
                    'select'    => $select,
                    'update_at' =>\Tools::getDateTimeByTime()
                ));
            }else{
                if($goods_num > 0) {
                    if ($type == 0) {
                        $res = $shopCartModel->incNum($where, 'goods_num', 1);
                        $shopCartModel->saveData($where, array(
                            'select' => $select,
                            'update_at' => \Tools::getDateTimeByTime()
                        ));
                    } else {
                        if ($cartInfo['goods_num'] == 1) {
                            //移除记录
                            $res = $shopCartModel->delData($where);
                        } else {
                            $res = $shopCartModel->decNum($where, 'goods_num', 1);
                            $shopCartModel->saveData($where, array(
                                'select' => $select,
                                'update_at' => \Tools::getDateTimeByTime()
                            ));
                        }
                    }
                }else{
                    $res = $shopCartModel->saveData($where, array(
                                'select' => $select,
                                'update_at' => \Tools::getDateTimeByTime()
                            ));
                }
            }
            if($res){
                 return \Tools::returnMsg(true,$res,$this->default_type);
            }else{
                 return \Tools::returnMsg(false,array(
                    'code'  => '10006',
                    'message'=>'更新失败'
                ),$this->default_type);
            }
        }else {
            return \Tools::returnMsg(true, array(), $this->default_type);
        }
    }

    /**
     * 提交购物车选择商品
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function uppay(){
        if($this->request->debug != 1){
            $goods_ids = input('id','','trim,intval');//商品id拼接的字符串
            $tokeninfo = $this->request->tokeninfo;
            if(empty($tokeninfo)){
                return \Tools::returnMsg(false,array(
                    'code'  => '100001',
                    'message'=>'未登录  请先登录'
                ),$this->default_type);
            }
            if(empty($goods_ids)){
                return \Tools::returnMsg(false,array(
                    'code'  => '10004',
                    'message'=>'参数有误'
                ),$this->default_type);
            }
            //查一下库存
            $detailModel = new \app\api\model\ShopGoodsItem();
            $shopCartModel = new \app\api\model\ShopCart();
            $goods_ids = explode(',', $goods_ids);
            foreach($goods_ids  as &$goods_id){
                $detail = $detailModel->getOne(array(
                    'id'    => $goods_id,
                    'status'=> 1
                ),'stock_total,goods_sku');
                if(empty($detail)){
                     return \Tools::returnMsg(false,array(
                        'code'  => '10004',
                        'message'=>'商品参数有误'
                    ),$this->default_type);
                }
                $shopCartInfo = $shopCartModel->getOne(array(
                    'user_id'  => $tokeninfo['id'],
                    'goods_id'  =>$goods_id
                ),'id,goods_num');
                if(empty($shopCartInfo)){
                    return \Tools::returnMsg(false,array(
                        'code'  => '10004',
                        'message'=>'购物车参数有误'
                    ),$this->default_type);
                }
                if($detail['stock_total'] < $shopCartInfo['goods_num']){
                    return \Tools::returnMsg(false,array(
                        'code'  => '10005',
                        'message'=>'库存不足'
                    ),$this->default_type);
                }
            }
            $res = $shopCartModel->updateCartData(array(
                'user_id'   => $tokeninfo['id']
            ),'goods_id',implode(',',$goods_ids),array(
                'select'    =>1,
                'update_at' => \Tools::getDateTimeByTime()
            ));
            if($res){
                return \Tools::returnMsg(true,$res,$this->default_type);
            }else{
                return \Tools::returnMsg(false,array(
                        'code'  => '10009',
                        'message'=>'更新失败'
                    ),$this->default_type);
            }
        }else{
            return \Tools::returnMsg(true,1,$this->default_type);
        }
    }
    /**
     * PUT
     * 删除购物车中商品
     * @return array|string
     */
    public function delete(){
        if($this->request->debug != 1){
            $goods_id = input('id','','trim,intval');//商品id

            \Common::addlog('deletecart',$goods_id);
            $tokeninfo = $this->request->tokeninfo;
            if(empty($tokeninfo)){
                return \Tools::returnMsg(false,array(
                    'code'  => '100001',
                    'message'=>'未登录  请先登录'
                ),$this->default_type);
            }
            if(empty($goods_id)){
                return \Tools::returnMsg(false,array(
                    'code'  => '10004',
                    'message'=>'参数有误'
                ),$this->default_type);
            }
            $shopCartModel = new \app\api\model\ShopCart();
            $where = array(
                        'user_id'   => $tokeninfo['id'],
                        'goods_id' => $goods_id
                    );
            $cartInfo = $shopCartModel->getOne($where,'id,goods_num');
            if(empty($cartInfo)){
                return \Tools::returnMsg(false,array(
                    'code'  => '10004',
                    'message'=>'参数有误'
                ),$this->default_type);
            }
            $res = $shopCartModel->delData($where);
            if($res){
                 return \Tools::returnMsg(true,$res,$this->default_type);
            }else{
                 return \Tools::returnMsg(false,array(
                    'code'  => '10006',
                    'message'=>'删除失败'
                ),$this->default_type);
            }
        }
        return \Tools::returnMsg(true,array(),$this->default_type);
    }
}
